package com.jack.netty.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by jack on 15/12/11.
 */
public class NetUtil {

    /**
     * @param side 表示要查询的是内网地址还是外网地址
     * 0 查询内网地址
     * 1 查询外网地址
     * 2 查询所有地址
     * @return 所有可用的IP地址集合
     */
    public static List<String> getAllIps(int side) {
        List<String> ipList = new LinkedList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaceList = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface = null;
            InetAddress inetAddress = null;
            Enumeration<InetAddress> inetAddressList = null;

            while (networkInterfaceList.hasMoreElements()) {
                networkInterface = networkInterfaceList.nextElement();
                inetAddressList = networkInterface.getInetAddresses();
                while (inetAddressList.hasMoreElements()) {
                    inetAddress = inetAddressList.nextElement();
                    if (inetAddress != null
                            && inetAddress instanceof Inet4Address
                            && !inetAddress.isLoopbackAddress()) {
                        switch (side) {
                            case 0:
                                if (inetAddress.isSiteLocalAddress()) {
                                    ipList.add(inetAddress.getHostAddress());
                                }
                                break;
                            case 1:
                                if (!inetAddress.isSiteLocalAddress()) {
                                    ipList.add(inetAddress.getHostAddress());
                                }
                                break;
                            case 2:
                                ipList.add(inetAddress.getHostAddress());
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("获取IP错误:" + e.getMessage());
        }
        return ipList;
    }


    public static void main(String[] args){
        List<String> ips = NetUtil.getAllIps(2);
        for(String ip : ips){
            System.out.println(ip);
        }
    }
}
